import axios from "axios";
import { UniAdapter } from "uniapp-axios-adapter";
import {serviceBaseUrl} from "@/config.js"

const domainUrl = serviceBaseUrl;
const request_timeout = 30000;
const axiosErrorMsg = '网络异常';

const service = axios.create({
	baseURL: domainUrl,
	timeout: request_timeout,
	adapter: UniAdapter
})
service.defaults.withCredentials = true;

function getSystemInfo() {
	try{
		return uni.getSystemInfoSync();
	}catch(e) {
		console.log('获取系统信息失败...');
	}
}

service.interceptors.request.use(
	config => {
		//添加设备信息
		var deviceInfo = getSystemInfo();
		console.log(deviceInfo);
		config.headers['terminalType'] = deviceInfo.platform;
		config.headers['phonetype'] = deviceInfo.model;
		config.headers['Content-Type'] = 'application/json';
		config.headers['Authorization'] = uni.getStorageSync('token') || '';
		console.log(config.headers);
		return config;
	},
	error => {
		console.log('发送请求失败: ' + error.toJSON());
		return Promise.reject(axiosErrorMsg);
	}
)


service.interceptors.response.use(
	response => {
		//data
		const res = response.data;

		//打印请求日志，方便调试
		console.log('请求地址：' + response.config.baseURL + response.config.url);
		if (response.config.params) {
			console.log('参数：' + JSON.stringify(response.config.params));
		}
		if (response.config.data) {
			console.log('参数：' + JSON.stringify(response.config.data));
		}
		console.log(res);

		//根据状态，返回数据
		if (res.code !== 200) {
			return Promise.reject(res);
		} else {
			return res;
		}
	},

	error => {
		console.log('请求地址：' + error.config.baseURL + error.config.url);
		console.log('请求失败: ' + error.toJSON());
		console.log(error);
		return Promise.reject(axiosErrorMsg);
	}
)

export function postMethod(rawUrl, params = {}) {
	return service({
		method: "post",
		url:rawUrl,
		data: params
	});
}

export function getMethod(rawUrl, params = {}) {
	return service({
		method: "get",
		url:rawUrl,
		params
	});
}